package com.code.generator.cn.controller;

import com.code.generator.cn.entity.CoderField;
import com.code.generator.cn.entity.CoderTable;
import com.code.generator.cn.service.ICoderFieldService;
import com.code.generator.cn.service.ICoderTableService;
import com.code.generator.cn.util.*;
import com.code.generator.cn.util.base.*;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
@Slf4j
public class CreateController {

    @Autowired
    private ICoderFieldService coderFieldService;


    @Autowired
    private ICoderTableService coderTableService;


    @Autowired
    private Configuration configuration;

    @Value("${upload.path}")
    private String uploadPath;

    @Autowired
    private ZipUtil zipUtil;


    /**
     * 项目生成主页面
     *
     * @return
     */
    @RequestMapping("/toCreate")
    public ModelAndView toUpdate(HttpServletRequest request, @RequestParam String id) {
        ModelAndView modelAndView = new ModelAndView("/main/create");
        modelAndView.addObject("obj", coderTableService.getById(id));
        return modelAndView;
    }


    /**
     * 项目生成主页面
     *
     * @return
     */
    @RequestMapping("/create")
    public void create(HttpServletRequest request, @RequestParam String id, @RequestParam String create, HttpServletResponse response) {

        //创建项目的路径将项目创建在 templete下的rar 文件中
        File path = null;
        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os = null; //输出流
        File downFile=null;
        CoderTable coderTable = coderTableService.getById(id);
        log.info("开始创建项目，项目路径为："+uploadPath);
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + coderTable.getModifyName()+".zip");


        try {
            createZip(create,id,uploadPath);
            String zipName=uploadPath+coderTable.getModifyName()+".zip";
            downFile=  new File(zipName);
            os = response.getOutputStream();
            fis = new FileInputStream(downFile);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
                os.flush();
            }
            log.info("----------file download" +coderTable.getModifyName()+".zip");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                fis.close();
                downFile.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建压缩文件
     * @param create 要生成的模板
     * @param id  生成表的id
     * @param uploadPath 生成的文件的基本路径
     */
    private void createZip(String create,String id, String uploadPath) {
        //获取要生成的模板
        String[] createModels = create.split(",");
        //获取要生成的表对象
        CoderTable coderTable = coderTableService.getById(id);
        if(StringUtils.isBlank(coderTable.getPackageName())){
            throw  new RuntimeException("请设置生成的包名");
        }

        String projPath=uploadPath+coderTable.getModifyName()+"/";
        MyFileUtil.createFileDir(projPath);
        log.info("项目生成路径为："+projPath);

        //获取表字段
        List<CoderField> coderFields = coderFieldService.getListByTableId(id);
        if (createModels.length == 0) {
            return;
        }
        try {
            for (String createModel : createModels) {
                if (createModel.equals("entity")) {
                    EntityUtil.createEntity(coderTable, coderFields, configuration,projPath);
                    ConfigUtil.createMapperConfig(coderTable, coderFields, configuration,projPath);
                }
                if (createModel.equals("mapper")) {
                    MapperUtil.createMapper(coderTable, coderFields, configuration,projPath);
                    MapperUtil.createMapperXml(coderTable, coderFields, configuration,projPath);
                    VoUtil.createQueryDto(coderTable, coderFields, configuration,projPath);
                    VoUtil.createVo(coderTable, coderFields, configuration,projPath);
                    VoUtil.createInputDto(coderTable, coderFields, configuration,projPath);
                }if(createModel.equals("service")){
                    ServiceUtil.createService(coderTable, coderFields, configuration,projPath);
                }if(createModel.equals("controller")){
                    ControllerUtil.createController(coderTable, coderFields, configuration,projPath);
                    ConfigUtil.createSwaggerConfig(coderTable, coderFields, configuration,projPath);
                }if(createModel.equals("vue")){
                   // VueUtil.createVue(coderTable,coderFields,configuration,projPath);
                }
            }

            /**
             * 压缩项目 将项目压缩成zip文件
             */
            zipUtil.dozip(projPath,uploadPath+coderTable.getModifyName()+".zip");

            /**
             * 最后删除掉生成的文件
             */
            File proFile=new  File(projPath);
            FileUtils.deleteDirectory(proFile);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
